class Solution {

    Set<Integer> ts = new HashSet<>();
    int n;

    public int bfs(int[][] graph, int x) {
        Deque<Integer> q = new ArrayDeque<>();
        q.add(x);
        Set<Integer> vis = new HashSet<>();
        vis.add(x);
        while (!q.isEmpty()) {
            int u = q.poll();
            for (int v = 0; v < n; v++) {
                if (graph[u][v] == 0 || vis.contains(v)) {
                    continue;
                }
                if (ts.contains(v)) {
                    return 0;
                }
                q.add(v);
                vis.add(v);
            }
        }
        return vis.size();
    }

    public int minMalwareSpread(int[][] graph, int[] initial) {
        n = graph.length;
        for (int v : initial) {
            ts.add(v);
        }
        Arrays.sort(initial);
        int ans = -1, mx = -1;
        for (int v : initial) {
            int cur = bfs(graph, v);
            if (cur > mx) {
                mx = cur;
                ans = v;
            }
        }
        return ans;
    }
}